import React from 'react';
import {connect} from 'react-redux';
import {browserHistory} from 'react-router';
import fetch from 'isomorphic-fetch';
import {logIn,fetchUser} from '../actions/actions';
import FileUpload from '../components/FileUpload';

class HomePage extends React.Component{
    constructor(props){
        super(props);
        this.handleClick = this.handleClick.bind(this)
        this.state = {
            name: '',
            passwd: '',
            fileList: [],
        };
    }

    handleChange = (info) => {
        let fileList = info.fileList;

        // 1. Limit the number of uploaded files
        //    Only to show two recent uploaded files, and old ones will be replaced by the new
        fileList = fileList.slice(-1);

        // 2. read from response and show file link
        fileList = fileList.map((file) => {
          if (file.response) {
            // Component will show file.url as link
            file.url = file.response.url;
          }
          return file;
        });

        // 3. filter successfully uploaded files according to response from server
        fileList = fileList.filter((file) => {
          if (file.response) {
            return file.response.status === 'success';
          }
          return true;
        });

        this.setState({ fileList });
      }

    handleClick(){
        const {dispatch} = this.props;
        const name = this.state.name,
            passwd = this.state.passwd;
        const content = JSON.stringify({
                name,
                passwd
            })
        fetch('/api/log',{
            method: 'POST',
            headers:{
                "Content-Type": "application/json",
                "Content-Length": content.length.toString()
            },
            body: content
        }).then(res=>{
            if(res.ok){
                return res.json()
            }
        }).then(token=>{
                if(token){
                    dispatch(logIn({name}))
                    localStorage.setItem('token',token)
                    dispatch(fetchUser())
                    browserHistory.push('/')
                } else {
                }
        })
    }
    render(){
        return (
            <div>
                here, we can put some publish contents of the group
                <br />
                    <FileUpload action="/api/uploadDocs" onFileUpload={(fileList)=>{console.log('xxxx', fileList)}}/>
            </div>
        )
    }
}
function mapStateToProps(state) {
  const { user } = state
  return {
    user
  }
}
export default connect(mapStateToProps)(HomePage)
